package initialize

import (
	"github.com/gin-gonic/gin/binding"
	zh "github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

//gin > 1.4.0
//将验证器错误翻译成中文

var (
	uni   *ut.UniversalTranslator
	Trans ut.Translator
)

func InitValidate() {
	//注册翻译器
	zhT := zh.New()
	uni = ut.New(zhT, zhT)

	Trans, _ = uni.GetTranslator("zh")

	//获取gin的校验器
	validate := binding.Validator.Engine().(*validator.Validate)
	//注册翻译器
	zh_translations.RegisterDefaultTranslations(validate, Trans)
}

// Translate 翻译错误信息
func Translate(err error) map[string][]string {

	var result = make(map[string][]string)

	errors := err.(validator.ValidationErrors)

	for _, err := range errors {
		result[err.Field()] = append(result[err.Field()], err.Translate(Trans))
	}
	return result
}
